<?php

class App_Model_DbTable_Settings extends Ext_Db_Table  
{  
	/** Table name */  
    protected $_name = 'settings';
    
	public function getSettings1($id)
	{
		$id = (int)$id;
		$row = $this->fetchRow('id = ' . $id);
		if (!$row) {
			//throw new Exception("Count not find row $id");
		}
		return $row->toArray();
	}
	
    public function getSettings2($k)
	{
		$filter=new Zend_Filter_StripTags();
		$k = $filter->filter( (string)$k );
		$row = $this->fetchRow("k = '" . $k. "'");
		if ($row) {
			return $row->toArray();
		}
		else{
			//throw new Exception("Count not find row $id");
		}
	}
	
	public function getSettingsAll()
	{
		$settingsAll = $this->fetchAll()->toArray();
		//print_r($settingsAll);
		
		return $settingsAll;
	}

	public function AddSettingsAllRow($settingsArray)
	{
		if(is_array($settingsArray))
		{
			foreach($settingsArray as $k=>$v)
			{
				if($k=='button')
				{
					continue;
				}
				
				$inputArray = array('k'=>$k, 'v'=>$v);
				$this->addSettings($inputArray);
			}
		}
		
		return "";
	}
	
	public function addSettings($inputArray)
	{
		$k = $inputArray['k'];
		$settingsRow = $this->getSettings2($k);
		if($settingsRow)
		{
			$this->addSettingsOld($inputArray, $k);
		}
		else 
		{
			$this->addSettingsNew($inputArray);
		}
		
		return "";
	}
	
	public function addSettingsNew($inputArray)
	{
		$this->getAdapter()->beginTransaction();//Zend_Db_Adapter会回到自动commit模式下，直到你再次调用 beginTransaction()方法
		// 以"列名"=>"数据"的格式格式构造插入数组,插入数据行
		$row = array (
			'k'     	=> $inputArray['k'],
			'v'     	=> $inputArray['v'],
		);
		try {
			// 插入数据行并返回插入的行数
			$rows_affected = $this->insert($row);
			// 最后插入的数据id   
			$last_insert_id = $this->getAdapter()->lastInsertId();
			$this->getAdapter()->commit();// 事务提交
		}catch (Exception $e){
			$this->getAdapter()->rollBack();
			trigger_error($e->getMessage(), E_USER_WARNING);
		}
		return $last_insert_id;
	}
	
	public function addSettingsOld($inputArray, $k)
	{
		$this->getAdapter()->beginTransaction();//Zend_Db_Adapter会回到自动commit模式下，直到你再次调用 beginTransaction()方法
		// 以"列名"=>"数据"的格式格式构造插入数组,插入数据行
		$row = array (
			'v'     	=> $inputArray['v'],
		);
		try {
			
			$db = $this->getAdapter();
			$where = $db->quoteInto(" k = ? ", $k);
			$rows_affected = $this->update($row, $where);
			$this->getAdapter()->commit();// 事务提交
		}catch (Exception $e){
			$this->getAdapter()->rollBack();
			trigger_error($e->getMessage(), E_USER_WARNING);
		}
		return "";
	}
}  

